#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ford UK NGc2 爬虫Drive模块
专门处理动力系统配置的抓取和数据提取
"""

import time
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from .car_object import CarObject


class DriveHandler:
    """Drive配置处理器"""
    
    def __init__(self, driver, wait, navigation_handler):
        """
        初始化Drive处理器
        
        Args:
            driver: WebDriver实例
            wait: WebDriverWait实例
            navigation_handler: 导航处理器实例
        """
        self.driver = driver
        self.wait = wait
        self.navigation_handler = navigation_handler
    
    def scrape_drive_data(self):
        """
        抓取Drive页面的数据
        
        Returns:
            list: Drive选项列表
        """
        print("    🚗 开始抓取Drive选项...")
        
        try:
            # 步骤1：导航到Drive页面
            if not self.navigate_to_drive_page():
                print("    ❌ 无法进入Drive页面")
                return []
            
            # 步骤2：等待Drive页面加载
            print("    ⏳ 等待Drive页面加载...")
            time.sleep(3)
            
            # 步骤3：提取Drive选项
            drive_options = self.extract_drive_options()
            
            if drive_options:
                print(f"    ✅ 成功抓取到 {len(drive_options)} 个Drive选项")
                for i, drive in enumerate(drive_options, 1):
                    print(f"      {i}. {drive.get('name', 'Unknown')} - {drive.get('price', 'N/A')}")
            else:
                print("    ⚠️  未找到Drive选项")
            
            return drive_options
            
        except Exception as e:
            print(f"    ❌ 抓取Drive数据时出错: {e}")
            return []
    
    def navigate_to_drive_page(self):
        """
        导航到Drive配置页面
        
        Returns:
            bool: 是否成功进入Drive页面
        """
        print(f"      🧭 导航到Drive页面...")
        
        try:
            # 方法1：查找导航栏中的Drive按钮
            nav_state = self.navigation_handler.get_navigation_state()
            if nav_state and 'Drive' in nav_state:
                drive_nav_info = nav_state['Drive']
                
                if (drive_nav_info.get('enabled', False) and 
                    not drive_nav_info.get('current', False)):
                    
                    drive_element = drive_nav_info['element']
                    print(f"      ✓ 找到Drive导航按钮")
                    
                    self.driver.execute_script("arguments[0].click();", drive_element)
                    time.sleep(2)
                    
                    if self.verify_drive_page_loaded():
                        print("      ✅ 通过导航栏进入Drive页面")
                        return True
            
            # 方法2：直接查找Drive相关链接
            drive_selectors = [
                'a[href*="drive"]',
                'button[data-testid*="drive"]',
                '[class*="drive"] a',
                'nav a:contains("Drive")'
            ]
            
            for selector in drive_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for element in elements:
                        if element.is_displayed() and element.is_enabled():
                            print(f"      ✓ 找到Drive链接: {selector}")
                            element.click()
                            time.sleep(2)
                            
                            if self.verify_drive_page_loaded():
                                print("      ✅ 通过直接链接进入Drive页面")
                                return True
                except Exception:
                    continue
            
            # 方法3：检查当前URL是否已经包含drive相关内容
            current_url = self.driver.current_url.lower()
            if 'drive' in current_url:
                print("      ✓ 当前URL显示已在Drive页面")
                return self.verify_drive_page_loaded()
            
            print("      ❌ 所有导航方法都失败")
            return False
            
        except Exception as e:
            print(f"      ❌ 导航到Drive页面时出错: {e}")
            return False
    
    def verify_drive_page_loaded(self):
        """
        验证Drive页面是否已加载
        
        Returns:
            bool: 是否已加载Drive页面
        """
        try:
            # 检查方法1：查找Drive相关的页面元素
            drive_indicators = [
                'div[data-testid*="drive"]',
                '[class*="drive-option"]',
                'button[class*="DriveOption"]',
                '[class*="ProductTile"][class*="Drive"]',
                'div[role="radio"][data-testid*="drive"]',
            ]
            
            for selector in drive_indicators:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    if elements:
                        print(f"        ✓ Drive页面验证成功: 找到 {len(elements)} 个Drive元素")
                        return True
                except Exception:
                    continue
            
            # 检查方法2：页面标题或URL
            current_url = self.driver.current_url.lower()
            page_title = self.driver.title.lower()
            
            if 'drive' in current_url or 'drive' in page_title:
                print("        ✓ Drive页面验证成功: URL或标题包含drive")
                return True
            
            # 检查方法3：导航状态
            nav_state = self.navigation_handler.get_navigation_state()
            if nav_state and 'Drive' in nav_state:
                if nav_state['Drive'].get('current', False):
                    print("        ✓ Drive页面验证成功: 导航状态显示当前在Drive页面")
                    return True
            
            print("        ❌ Drive页面验证失败")
            return False
            
        except Exception as e:
            print(f"        ❌ 验证Drive页面时出错: {e}")
            return False
    
    def extract_drive_options(self):
        """
        从Drive页面提取所有Drive选项
        
        Returns:
            list: Drive选项列表
        """
        print("        🔍 开始提取Drive选项...")
        
        try:
            drive_options = []
            
            # Drive选项的多种可能选择器
            drive_selectors = [
                'div[role="radio"][data-testid*="drive"]',
                'button[class*="DriveOption"]',
                '[class*="ProductTile"] div[data-testid*="drive"]',
                'div[class*="option"][data-testid*="drive"]',
                'div[data-cy*="drive"]'
            ]
            
            elements_found = []
            
            # 尝试多种选择器
            for selector in drive_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    if elements:
                        elements_found = elements
                        print(f"        使用选择器 '{selector}' 找到 {len(elements)} 个Drive元素")
                        break
                except Exception:
                    continue
            
            if not elements_found:
                print("        ⚠️  未找到Drive选项元素")
                return []
            
            # 提取每个Drive选项的数据
            for i, element in enumerate(elements_found, 1):
                if element.is_displayed():
                    drive_data = self.extract_drive_option_data(element)
                    if drive_data:
                        drive_options.append(drive_data)
                        print(f"          ✓ 提取Drive {i}: {drive_data['name']} - {drive_data['price']}")
            
            return drive_options
            
        except Exception as e:
            print(f"        ❌ 提取Drive选项时出错: {e}")
            return []
    
    def extract_drive_option_data(self, element):
        """
        从Drive选项元素中提取数据
        
        Args:
            element (WebElement): Drive选项元素
            
        Returns:
            dict or None: Drive选项数据
        """
        try:
            name = ''
            price = ''
            description = ''
            
            # 提取Drive名称 - 尝试多种方法
            name_selectors = [
                '[class*="title"]',
                '[class*="name"]',
                'strong',
                'h3, h4, h5',
                '[data-testid*="title"]'
            ]
            
            for name_selector in name_selectors:
                try:
                    name_element = element.find_element(By.CSS_SELECTOR, name_selector)
                    name_text = name_element.text.strip()
                    if name_text and len(name_text) > 1:
                        name = name_text
                        break
                except Exception:
                    continue
            
            # 如果还没找到名称，使用元素的整体文本
            if not name:
                name = element.text.strip().split('\n')[0]
            
            # 提取价格信息
            price_selectors = [
                '[class*="price"]',
                'span:contains("£")',
                '[data-testid*="price"]',
                'strong:contains("£")'
            ]
            
            for price_selector in price_selectors:
                try:
                    price_element = element.find_element(By.CSS_SELECTOR, price_selector)
                    price_text = price_element.text.strip()
                    if '£' in price_text:
                        price = price_text
                        break
                except Exception:
                    continue
            
            # 如果没有找到价格，检查元素文本中是否包含价格
            if not price:
                element_text = element.text
                if '£' in element_text:
                    lines = element_text.split('\n')
                    for line in lines:
                        if '£' in line:
                            price = line.strip()
                            break
            
            # 默认价格
            if not price:
                price = 'Standard'
            
            # 提取描述信息
            try:
                description_elements = element.find_elements(By.CSS_SELECTOR, 'p, div[class*="description"]')
                for desc_elem in description_elements:
                    desc_text = desc_elem.text.strip()
                    if desc_text and desc_text != name and '£' not in desc_text:
                        description = desc_text
                        break
            except Exception:
                pass
            
            if name:
                return {
                    'name': name,
                    'price': price,
                    'description': description,
                    'element': element
                }
            
            return None
            
        except Exception as e:
            print(f"          ❌ 提取Drive选项数据时出错: {e}")
            return None
    
    def select_drive_option(self, drive_option):
        """
        选择指定的Drive选项
        
        Args:
            drive_option (dict): Drive选项数据
            
        Returns:
            bool: 是否成功选择
        """
        drive_name = drive_option.get('name', '')
        print(f"        🎯 选择Drive选项: {drive_name}")
        
        try:
            drive_element = drive_option.get('element')
            
            if drive_element and drive_element.is_displayed():
                # 尝试找到对应的选择按钮
                select_button = self.find_selected_button_for_drive(drive_element)
                
                if select_button:
                    try:
                        self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", select_button)
                        time.sleep(0.5)
                        select_button.click()
                        time.sleep(2)
                        print(f"        ✅ 成功选择Drive: {drive_name}")
                        return True
                    except Exception as e:
                        print(f"        ❌ 点击Drive选择按钮失败: {e}")
                
                # 如果找不到特定按钮，尝试点击整个Drive元素
                try:
                    self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", drive_element)
                    time.sleep(0.5)
                    drive_element.click()
                    time.sleep(2)
                    print(f"        ✅ 通过点击Drive元素成功选择: {drive_name}")
                    return True
                except Exception as e:
                    print(f"        ❌ 点击Drive元素失败: {e}")
            
            # 最后尝试通过通用选择按钮
            generic_buttons = self.driver.find_elements(By.CSS_SELECTOR, 'button[class*="Select"], button:contains("Select")')
            for button in generic_buttons:
                if button.is_displayed():
                    try:
                        button.click()
                        time.sleep(2)
                        print(f"        ✅ 使用通用Select按钮选择Drive")
                        return True
                    except Exception:
                        continue
            
            print(f"        ❌ 未找到可点击的Drive选项: {drive_name}")
            return False
            
        except Exception as e:
            print(f"        ❌ 选择Drive选项时出错: {e}")
            return False
    
    def find_selected_button_for_drive(self, drive_element):
        """
        查找Drive元素对应的选择按钮
        
        Args:
            drive_element (WebElement): Drive选项元素
            
        Returns:
            WebElement or None: 选择按钮元素
        """
        try:
            # 在Drive元素内部查找按钮
            button_selectors = [
                'button[class*="Select"]',
                'button:contains("Select")',
                'button[data-testid*="select"]',
                'a[class*="Select"]',
                'button'
            ]
            
            for selector in button_selectors:
                try:
                    buttons = drive_element.find_elements(By.CSS_SELECTOR, selector)
                    for button in buttons:
                        if button.is_displayed() and button.is_enabled():
                            button_text = button.text.lower()
                            if 'select' in button_text or button_text == '':
                                return button
                except Exception:
                    continue
            
            return None
            
        except Exception as e:
            print(f"          查找选择按钮时出错: {e}")
            return None
    
    def update_car_objects_with_drive_data(self, car_series, target_model, drive_data):
        """
        使用Drive数据更新CarObject实例
        根据新业务逻辑：为每个Drive创建独立的CarObject
        
        Args:
            car_series (CarSeries): 车系对象
            target_model (str): 目标车型名称
            drive_data (list): Drive数据列表
        """
        print(f"    🔄 为 {target_model} 创建基于Drive的CarObject...")
        
        try:
            # 查找并移除现有的目标车型
            original_car_object = None
            for i, car_object in enumerate(car_series.car_object_list):
                if car_object.model_name.lower() == target_model.lower():
                    original_car_object = car_object
                    car_series.car_object_list.pop(i)
                    break
            
            if not original_car_object:
                print(f"    ⚠️  未找到车型 {target_model} 的原始 CarObject")
                return
            
            # 为每个Drive创建新的CarObject
            created_objects = 0
            for drive_option in drive_data:
                drive_name = drive_option.get('name', '')
                
                if drive_name:
                    # 创建新的CarObject，使用drive参数
                    new_car_object = CarObject(
                        series_name=original_car_object.series_name,
                        model_name=original_car_object.model_name,
                        price=original_car_object.price,
                        drive=drive_name  # 使用drive属性而不是drive_types
                    )
                    
                    # 复制其他属性
                    new_car_object.key_features = original_car_object.key_features.copy()
                    new_car_object.specifications = original_car_object.specifications.copy()
                    new_car_object.body_style = original_car_object.body_style
                    new_car_object.colors = original_car_object.colors.copy()
                    new_car_object.interiors = original_car_object.interiors.copy()
                    new_car_object.extras_list = original_car_object.extras_list.copy()
                    
                    # 添加Drive类型数据（同时保持新架构兼容性）
                    new_car_object.add_drive_type(
                        drive_name=drive_name,
                        price=drive_option.get('price', 'Standard'),
                        description=drive_option.get('description', '')
                    )
                    
                    # 添加到车系
                    car_series.add_car_object(new_car_object)
                    created_objects += 1
                    
                    print(f"      ✓ 创建CarObject: {target_model} + {drive_name}")
            
            print(f"    ✅ 共创建了 {created_objects} 个基于Drive的CarObject")
            
        except Exception as e:
            print(f"    ❌ 更新CarObject时出错: {e}")